<template>
  <view class="check-task-container">
    <!-- 查询条件 -->
    <uni-forms @submit="search" :model="queryParams">
      <uni-forms-item label="用户编码" name="userCode">
        <uni-easyinput v-model="queryParams.userCode" placeholder="请输入用户编码" />
      </uni-forms-item>

      <uni-forms-item label="用户名称" name="userName">
        <uni-easyinput v-model="queryParams.userName" placeholder="请输入用户名称" />
      </uni-forms-item>

      <uni-forms-item label="所在区域" name="userArea">
        <uni-data-select
            :key="areaListKey"
            :localdata="areaList"
            valuefield="value"
            labelfield="text"
            v-model="queryParams.userArea"
            @change="handleAreaChange"
            >
        </uni-data-select>
      </uni-forms-item>

      <view class="form-actions">
        <button @click="search" type="primary" size="mini" style="flex: 1; margin-right: 20rpx;">搜索</button>
        <button @click="reset" type="default" size="mini" style="flex: 1;">重置</button>
      </view>
    </uni-forms>

    <!-- 数据列表 -->
    <scroll-view scroll-y :scroll-top="scrollTop" @scroll="handleScroll" style="height: 100vh;">
        <uni-list v-if="list.length > 0">
            <uni-list-item 
                v-for="item in list" 
                :key="item.planArchiveId"
                :title="item.sgUserArchives.userName"
				:note="item.sgUserArchives.userCode"
                clickable
                :rightText="formatArea(item.sgUserArchives)"
                @click="goTask(item.planId,item.planArchiveId)" 
                />
        </uni-list>
        <uni-load-more :status="loadingStatus" v-if="list.length > 0" />
    </scroll-view>
  </view>
</template>

<script>
import { listCheckTasks } from '@/api/task/task';
//加载字典api
//TODO 向上滑动时翻页功能
import { getDictDatas } from '@/api/system/dict/data';

export default {
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userCode: '',
        userName: '',
        userArea: ''
      },
      areaList: [], // 区域字典数据
      selectedAreaLabel: '所有',
      total: 0,
      list: [],
      loadingStatus: 'more',
      areaListKey: 0, // 用于强制刷新区域选择组件
      scrollTop: 0
    };
  },
  onLoad() {
    this.loadAreaData();
    this.getList();
  },
  methods: {
    // 加载区域字典
    async loadAreaData() {
      getDictDatas('sg_area')
        .then(res => {
          this.areaList = res.rows.map(item => ({
            value: String(item.dictValue),
            text: item.dictLabel
          }));
          this.areaList.unshift({ value: '', text: '所有' });
        })
        .catch(error => {
          uni.showToast({ title: '区域数据加载失败', icon: 'none' });
          this.areaList = [{ value: '', text: '所有' }];
        });
    },
    // 格式化 note 显示内容
    formatArea(user) {
        if (!user) return '';
        return this.areaList.find(item => item.value === user.userArea).text;
    },

    // 获取数据列表
    async getList() {
      listCheckTasks(this.queryParams)
        .then(res => {
          console.log('加载巡检任务成功:',res);
          this.list = res.rows;
          this.total = res.total; 
          this.loadingStatus = this.list.length >= this.total ? 'noMore' : 'more';
        }).catch(error => {
          console.error('加载巡检任务失败:'+error);
          this.list = []; // 设置为空列表或默认值，防止后续出错
        });
    },

    // 搜索
    search() {
      this.pageNum = 1;
      this.getList();
    },

    // 重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        userCode: '',
        userName: '',
        userArea: ''
      };
      this.selectedAreaLabel = '所有';
      this.getList();
    },

    // 区域选择变化
    handleAreaChange(index) {
    //   const index = e.detail.value;
    //   const selected = this.areaList[index];
    //   console.log('index:', index);
    //   console.log('selected:', selected);
    //   if (selected) {
    //     console.log('选中区域:', selected);
    //   }
    //   this.selectedAreaLabel = selected.label;
    },
    // 加载更多
    handleScroll() {
        if (this.loadingStatus !== 'more') return;
        this.queryParams.pageNum += 1;
        this.getList();
    },

    // 跳转到详情
    goTask(planId,planArchiveId) {
        this.$tab.navigateTo('/pages/work/task/record?planId='+planId+'&planArchiveId='+planArchiveId);
    }
  }
};
</script>

<style lang="scss" scoped>
.check-task-container {
  padding: 20rpx;
}

// .search-form {
//   background-color: #f5f5f5;
//   padding: 20rpx;
//   border-radius: 8rpx;
// }

// .form-item {
//   margin-bottom: 20rpx;
//   display: flex;
//   align-items: center;
// }

// .form-item text {
//   width: 160rpx;
//   font-size: 28rpx;
// }

// .form-item input {
//   flex: 1;
//   padding: 10rpx;
//   border: 1px solid #ddd;
//   border-radius: 4rpx;
// }

.form-actions {
  display: flex;
  padding: 20rpx;
}

.actions .uni-btn {
  margin: 0 10rpx;
}

</style>